<?php
/**
 * golangshop商城系统 - 团队十年电商经验汇集巨献!
 * =========================================================
 * Copy right 2019-2029 杭州瑞璞玉数字科技有限公司, 保留所有权利。
 * ----------------------------------------------
 * 官方网址: https://www.golangshop.com
 * =========================================================
 */

namespace addon\form\event;

use addon\form\model\Form;

/**
 * 订单待付款
 */
class OrderCreate
{
    /**
     * @return multitype:number unknown
     */
    public function handle($data)
    {
        $create_data = $data[ 'create_data' ] ?? [];
        if (isset($create_data[ 'form_data' ]) && !empty($create_data[ 'form_data' ])) {
            // 添加订单表单
            $form = new Form();
            if (isset($create_data[ 'form_data' ][ 'form_data' ])) {
                $res = $form->addFormData([
                    'site_id' => $create_data[ 'site_id' ],
                    'form_id' => $create_data[ 'form_data' ][ 'form_id' ],
                    'member_id' => $create_data[ 'member_id' ],
                    'relation_id' => $data[ 'order_id' ],
                    'form_data' => $create_data[ 'form_data' ][ 'form_data' ],
                    'scene' => 'order'
                ]);
                if ($res[ 'code' ] != 0) return $res;
            }

            // 添加商品表单
            if (isset($create_data[ 'form_data' ][ 'goods_form' ])) {
                $goods_list = array_column($create_data[ 'shop_goods_list' ][ 'goods_list' ], null, 'sku_id');
                foreach ($create_data[ 'form_data' ][ 'goods_form' ] as $sku_id => $form_item) {
                    $res = $form->addFormData([
                        'site_id' => $create_data[ 'site_id' ],
                        'form_id' => $form_item[ 'form_id' ],
                        'member_id' => $create_data[ 'member_id' ],
                        'relation_id' => isset($goods_list[ $sku_id ]) && isset($goods_list[ $sku_id ][ 'order_goods_id' ]) ? $goods_list[ $sku_id ][ 'order_goods_id' ] : 0,
                        'form_data' => $form_item[ 'form_data' ],
                        'scene' => 'goods'
                    ]);
                    if ($res[ 'code' ] != 0) return $res;
                }
            }
        }
        return success();
    }
}